//
//  QRViewController.m
//  PlantGoWorker
//
//  Created by 纪翀 on 16/2/24.
//  Copyright © 2016年 青希羽博. All rights reserved.
//

#import "QRViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "QRTableViewCell.h"

@interface QRViewController ()<AVCaptureMetadataOutputObjectsDelegate>
{
    NSMutableArray *_QRArray;
}
//捕捉会话
@property (nonatomic, strong) AVCaptureSession *captureSession;
//展示layer
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
//
@property (strong, nonatomic) CALayer *scanLayer;


@end

@implementation QRViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _scanLayer = nil;
    _captureSession = nil;
    
    [self initTabView];
    // Do any additional setup after loading the view from its nib.

}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self startReading];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initTabView
{
    _tabView.rowHeight = 64;
    _QRArray = [NSMutableArray arrayWithCapacity:5];
    [_tabView registerNib:[UINib nibWithNibName:@"QRTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
}

- (BOOL)startReading {
    NSError *error;
    
    //1.初始化捕捉设备（AVCaptureDevice），类型为AVMediaTypeVideo
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //2.用captureDevice创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    
    //3.创建媒体数据输出流
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    
    //4.实例化捕捉会话
    _captureSession = [[AVCaptureSession alloc] init];
    
    //4.1.将输入流添加到会话
    [_captureSession addInput:input];
    
    //4.2.将媒体输出流添加到会话中
    [_captureSession addOutput:captureMetadataOutput];
    
    //5.创建串行队列，并加媒体输出流添加到队列当中
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    //5.1.设置代理
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    
    //5.2.设置输出媒体数据类型为QRCode
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode, nil]];
    
    //6.实例化预览图层
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    
    //7.设置预览图层填充方式
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    //8.设置图层的frame
    [_videoPreviewLayer setFrame:_cameraView.layer.bounds];
    
    //9.将图层添加到预览view的图层上
    [_cameraView.layer addSublayer:_videoPreviewLayer];
    
    
    //10.设置扫描范围
    CGFloat XScale = 0;
    CGFloat TopScale = 32/_cameraView.bounds.size.height;
    CGFloat BottomScale = TopScale * 2;
    captureMetadataOutput.rectOfInterest = CGRectMake(0,0,1-TopScale,1);
//    captureMetadataOutput.rectOfInterest = CGRectMake(0,0,1,1);
//    captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
    NSLog(@"X:%f, Y:%f , W:%f, H:%f", _boxView.frame.origin.x, _boxView.frame.origin.y, _boxView.frame.size.width, _boxView.frame.size.height);
    NSLog(@"X:%f, Y:%f , W:%f, H:%f", _cameraView.frame.origin.x, _cameraView.frame.origin.y, _cameraView.frame.size.width, _cameraView.frame.size.height);
    
    //10.1.扫描框
    _boxView.layer.borderColor = [UIColor greenColor].CGColor;
    _boxView.layer.borderWidth = 1.0f;

    [_cameraView addSubview:_boxView];
    
    //10.2.扫描线
    _scanLayer = [[CALayer alloc] init];
    _scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
    _scanLayer.backgroundColor = [UIColor brownColor].CGColor;
    
    [_boxView.layer addSublayer:_scanLayer];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    
    [timer fire];
    
    //10.开始扫描
    [_captureSession startRunning];
    
    
    return YES;
}

-(void)stopReading{
    [_captureSession stopRunning];
    _captureSession = nil;
    [_scanLayer removeFromSuperlayer];
    [_videoPreviewLayer removeFromSuperlayer];
}

-(void)timerFireMethod//弹出框
{
    [_hintLabel setHidden:YES];
}


#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        //判断回传的数据类型
//        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode])
        {
            NSLog(@"二维码解析结果为：%@", [metadataObj stringValue]);

            
//                [self stopReading];
            Boolean match = NO;
            for (NSString *qr in _QRArray){
                if ([qr isEqualToString:[metadataObj stringValue]]){
                    match = YES;
                    break;
                }
            }
            if (!match){
                [_QRArray insertObject:[metadataObj stringValue] atIndex:0];
                AudioServicesPlaySystemSound(1108);
                dispatch_async(dispatch_get_main_queue(), ^(void){
                    [_tabView reloadData];
                });
            }
        }
    }
}

- (void)moveScanLayer:(NSTimer *)timer
{
    CGRect frame = _scanLayer.frame;
    CGFloat step = _boxView.frame.size.height/15;
    frame.origin.y += step;
    if (_boxView.frame.size.height < frame.origin.y) {
        frame.origin.y = 0;
        _scanLayer.frame = frame;
    }else{
        [UIView animateWithDuration:0.1 animations:^{
            _scanLayer.frame = frame;
        }];
    }
    NSLog(@"move!");
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_QRArray count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *qr = [_QRArray objectAtIndex:indexPath.row];
    QRTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.QRLabel.text = qr;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:{
            
            break;
        }
        default:
            break;
    }
}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setEditing:YES animated:YES];
    return UITableViewCellEditingStyleDelete;
}

//左滑cell时出现什么按钮 -> Delegate方法
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewRowAction *action0 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"取消" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"点击了取消按钮");
        
        
        // 收回左滑出现的按钮(退出编辑模式)
        tableView.editing = NO;
    }];
    
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        NSLog(@"点击了删除按钮");
        //  删除数据源
        [_QRArray removeObjectAtIndex:indexPath.row];
        //    刷新数据
        [tableView reloadData];
        //或者cell删除
        //[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }];
    
    return @[action1, action0];
}


////进入编辑模式，按下出现的编辑按钮后
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    [_QRArray removeObjectAtIndex:indexPath.row];
//    [tableView reloadData];
//    [tableView setEditing:NO animated:YES];
//}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (IBAction)backBtnClick:(id)sender {
    [self stopReading];
    [self.navigationController popViewControllerAnimated:YES];
//        [self startReading];
}
- (IBAction)commitBtnClick:(id)sender {
    
    
    NSString *token = [GlobalVar getVarName:@"token"];
    NSDictionary *postDic = @{
                              @"token":token,
                              @"storageId":_storageId,
                              @"stockroomId":_stockId,
                              @"barCodes":_QRArray
                              };
    [SendRequestClass commonRequest:@"/api/commitstocktake" postDic:postDic completionBlock:^(NSDictionary *succDic) {
        if ([[succDic objectForKey:@"code"] intValue] == SUCC_RESP)
        {
            NSLog(@"Success commitstocktake");
            NSArray *failArr = [[succDic objectForKey:@"data"] objectForKey:@"errorRes"];
            NSDictionary *dataDic = [succDic objectForKey:@"data"];
            BOOL isError = [[dataDic objectForKey:@"isError"] boolValue];
            if (!isError){
                [MyHint showHint:@"提交成功！"];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提交错误" message:@"以下条码不应出现在该客户租赁库" preferredStyle:UIAlertControllerStyleAlert];
                for (NSDictionary *barCodeDic in failArr){
                    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
                        textField.text = [barCodeDic objectForKey:@"id"];
                        [textField setBackgroundColor:[UIColor clearColor]];
                        textField.layer.borderColor = [UIColor clearColor].CGColor;
                        [textField setUserInteractionEnabled:NO];
                    }];
                }
                
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                }];
                [alertController addAction:okAction];
                [self presentViewController:alertController animated:YES completion:nil];
                
            }

        }
        else{
            NSLog(@"Fail commitstocktake");
            [MyHint showHint:[succDic objectForKey:@"message"]];
        }
        
    } failureBlock:^(NSDictionary *failDic) {
        NSLog(@"Network error");
        [MyHint showHint:@"网络出现故障"];
    }];
}

- (IBAction)lightBtnClick:(UIButton*)sender {
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch]) { // 判断是否有闪光灯
            // 请求独占访问硬件设备
            [device lockForConfiguration:nil];
            if (sender.tag == 0) {
                
                sender.tag = 1;
                [device setTorchMode:AVCaptureTorchModeOn]; // 手电筒开
            }else{
                
                sender.tag = 0;
                [device setTorchMode:AVCaptureTorchModeOff]; // 手电筒关
            }
            // 请求解除独占访问硬件设备
            [device unlockForConfiguration];
        }
    }
}

@end
